package com.example.demo_mysql_mybatisplus.util.easyexcel.exports.customized.selected;


import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.example.demo_mysql_mybatisplus.util.easyexcel.exports.customized.util.ExportUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 单元格下拉框处理器
 * */
@Data
@AllArgsConstructor
public class ContentSelectedRowWriteHandler<T> implements RowWriteHandler {

    private final Class<T> headerClass;

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder
            , Row row, Integer relativeRowIndex, Boolean isHead) {
        if(isHead){
            Map<String, ExcelSelectedResolve> selectedMap = getAnnotations(headerClass);
            Map<String,Integer>  cellPositionMap = ExportUtil.cellPosition( row );
            // 这里可以对cell进行任何操作
            Sheet sheet = writeSheetHolder.getSheet();
            DataValidationHelper helper = sheet.getDataValidationHelper();
            selectedMap.forEach((headName, excelSelectedResolve) -> {
                Integer index = cellPositionMap.get(headName) ;
                if(null!=index){
                    // 设置下拉列表的行： 首行，末行，首列，末列
                    CellRangeAddressList rangeList = new CellRangeAddressList(
                            excelSelectedResolve.getFirstRow(), excelSelectedResolve.getLastRow()
                            , index, index);
                    // 设置下拉列表的值
                    DataValidationConstraint constraint = helper.createExplicitListConstraint(excelSelectedResolve.getSource());
                    // 设置约束
                    DataValidation validation = helper.createValidation(constraint, rangeList);
                    // 阻止输入非下拉选项的值
                    validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
                    validation.setShowErrorBox(true);
                    validation.setSuppressDropDownArrow(true);
                    validation.createErrorBox("提示", "请输入下拉选项中的内容");
                    sheet.addValidationData(validation);
                }
            });
        }
    }

    /**
     * 解析表头类中的下拉框注解
     * @param headerClass 表头类
     * @param <T> 泛型
     * @return map
     */
    private <T> Map<String, ExcelSelectedResolve> getAnnotations(Class<T> headerClass) {
        Map<String, ExcelSelectedResolve> selectedMap = new HashMap<>();

        // getDeclaredFields(): 返回全部声明的属性；getFields(): 返回public类型的属性
        Field[] fields = headerClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++){
            Field field = fields[i];
            // 解析注解信息
            ExcelSelected selected = field.getAnnotation(ExcelSelected.class);
            ExcelProperty property = field.getAnnotation(ExcelProperty.class);
            if (selected != null && property!=null ) {
                ExcelSelectedResolve resolve = new ExcelSelectedResolve();
                String[] source = resolve.resolveSelectedSource(selected);
                if (source != null && source.length > 0){
                    resolve.setSource(source);
                    resolve.setFirstRow(selected.firstRow());
                    resolve.setLastRow(selected.lastRow());

                    selectedMap.put(property.value()[0], resolve);
                }
            }
        }
        return selectedMap;
    }

}
